
# 首页页面静态化 生成静态化的函数
from collections import OrderedDict
from goods.models import GoodsChannel,GoodsCategory
from django.template import loader
from django.conf import settings
import os
from contents.models import ContentCategory,Content



def generate_index_html():

    """
    生成首页静态页面：
    1、获取动态数据 —— 模版参数
    2、模版渲染 —— 模版参数填充到模版html页面中
    """

    # ============频道分组===========
    # categories = {} # python普通字典的键值对是无序的！
    categories = OrderedDict() # 有序字典，键值对顺序是固定的；

    channels = GoodsChannel.objects.order_by(
        # order_by传入多个字段排序，如果group_id一样，按照sequence排
        'group_id',
        'sequence'
    )

    for channel in channels:
        # channel: 每一个频道对象

        # 模版参数中，第一次遍历到该分组，那么就在categories添加一个
        # 新的key(该key就是group_id)
        if channel.group_id not in categories:
            categories[channel.group_id] = {
                "channels": [], # 当前频道组的1级分类
                "sub_cats": [] # 2级分类
            }

        # 构建当前分组的频道和分类信息
        cat1 = channel.category
        categories[channel.group_id]["channels"].append({
            "id": cat1.id,
            "name": cat1.name,
            "url": channel.url
        })

        # 所有父级分类是cat1这个1级别分类的2级分类
        cat2s = GoodsCategory.objects.filter(
            parent=cat1
        )
        for cat2 in cat2s:
            # cat2: 每一个2级分类对象
            cat3_list = [] # 根据cat2这个2级分类获取3级分类

            cat3s = GoodsCategory.objects.filter(
                parent=cat2
            )
            for cat3 in cat3s:
                # cat3: 每一个3级分类对象
                cat3_list.append({
                    "id": cat3.id,
                    "name": cat3.name
                })

            categories[channel.group_id]['sub_cats'].append({
                "id": cat2.id,
                "name": cat2.name,
                "sub_cats": cat3_list # 3级分类
            })

    # =====首页广告模板渲染======
    contents = {}

    content_cats = ContentCategory.objects.all()
    for content_cat in content_cats:
        contents[content_cat.key] = Content.objects.filter(category=content_cat,status=True).order_by('sequence')

    # =======模板页面渲染=====
    # 模板参数

    context = {
        'categories': categories,
        'contents': contents
    }

    template = loader.get_template('index.html')

    index_html = template.render(context=context)

    index_path = os.path.join(settings.GENERATED_STATIC_HTML_DIR, 'index.html')

    with open(index_path,'w') as f:
        f.write(index_html)